package com.example.websocketrabbitmq.websocket;

import com.example.websocketrabbitmq.entity.Msg;
import com.example.websocketrabbitmq.service.MsgService;
import com.example.websocketrabbitmq.websocket.utils.SpringContext;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;

/**
 * 创建处理类管理连接和消息
 */
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {
    private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
//    private final static String QUEUE_NAME = "test_queue";
    private final static String QUEUE_NAME = "printer";
    private MsgService msgService;

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        System.out.println("新连接：" + session.getId());

        // 获取MsgService实例
        this.msgService = SpringContext.getBean(MsgService.class);

        // 监听队列
       /* try {
            ConnectionFactory factory = new ConnectionFactory();
//            factory.setHost("localhost");
            factory.setHost("192.168.1.20");
            factory.setUsername("bailing");
            factory.setPassword("bailing123");

            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println("收到生产的消息: " + message);

//                sendMessage(session, message);
                // 广播消息给所有客户端
                broadcast(message);

                // 保存消息到数据库
                Msg msgBean = new Msg();
                msgBean.setMsg(message);
                this.msgService.save(msgBean);
            };
            channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
            });
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }*/
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);

        System.out.println("收到客户端发来的消息：" + message);

        // 处理业务逻辑后回复
//        sendMessage(session, "{\n" +
//                "  \"state\": \"已收到\",\n" +
//                "  \"message\":\"" + message + "\",\n" +
//                "  \"time\":\"" + formattedDateTime + "\"\n" +
//                "}");

        // 构建要广播的消息
        String responseMessage = "{\n" +
                "  \"state\": \"已收到\",\n" +
                "  \"message\":\"" + message + "\",\n" +
                "  \"time\":\"" + formattedDateTime + "\"\n" +
                "}";
        // 广播消息给所有客户端
        broadcast(responseMessage);
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        System.out.println("连接关闭：" + session.getId());
    }

    // 向指定客户端发送消息
    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 群发消息
    public static void broadcast(String message) {
        sessionMap.values().forEach(session -> sendMessage(session, message));
    }
}
